import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useAuthStore } from './auth'
import { v4 as uuidv4 } from 'uuid'

export const useAccountsStore = defineStore('accounts', () => {
  const accounts = ref([])
  const categories = ref(['工作', '个人', '社交媒体', '金融理财', '游戏娱乐', '购物网站'])
  const searchQuery = ref('')
  const selectedCategory = ref('全部')
  const loading = ref(false)

  // 计算属性
  const filteredAccounts = computed(() => {
    let filtered = accounts.value

    // 按分类筛选
    if (selectedCategory.value !== '全部') {
      filtered = filtered.filter(account => account.category === selectedCategory.value)
    }

    // 按搜索关键词筛选
    if (searchQuery.value) {
      const query = searchQuery.value.toLowerCase()
      filtered = filtered.filter(account =>
        account.title.toLowerCase().includes(query) ||
        account.username.toLowerCase().includes(query) ||
        account.url.toLowerCase().includes(query) ||
        (account.notes && account.notes.toLowerCase().includes(query))
      )
    }

    return filtered.sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt))
  })

  const favoriteAccounts = computed(() => {
    return accounts.value.filter(account => account.isFavorite)
  })

  const recentAccounts = computed(() => {
    return accounts.value
      .filter(account => account.lastUsed)
      .sort((a, b) => new Date(b.lastUsed) - new Date(a.lastUsed))
      .slice(0, 10)
  })

  // 数据操作方法
  const loadAccounts = async () => {
    try {
      loading.value = true
      const authStore = useAuthStore()
      const data = await window.electronAPI.loadData(authStore.masterPassword)
      accounts.value = data.accounts || []
    } catch (error) {
      console.error('加载账号数据失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  const saveAccounts = async () => {
    try {
      const authStore = useAuthStore()
      
      // 确保传递的是纯JavaScript对象，不包含任何函数或Proxy
      const cleanAccounts = JSON.parse(JSON.stringify(accounts.value))
      
      const success = await window.electronAPI.saveData({
        accounts: cleanAccounts,
        masterPassword: authStore.masterPassword
      })
      if (!success) {
        throw new Error('主进程返回保存失败')
      }
    } catch (error) {
      console.error('保存账号数据失败:', error)
      throw error
    }
  }

  const addAccount = async (accountData) => {
    const newAccount = {
      id: uuidv4(),
      ...accountData,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      lastUsed: null
    }
    
    try {
      // 先保存到后端，成功后再更新本地状态
      accounts.value.push(newAccount)
      await saveAccounts()
      return newAccount
    } catch (error) {
      // 如果保存失败，回滚本地状态
      const index = accounts.value.findIndex(acc => acc.id === newAccount.id)
      if (index !== -1) {
        accounts.value.splice(index, 1)
      }
      console.error('添加账号失败:', error)
      throw error
    }
  }

  const updateAccount = async (id, accountData) => {
    try {
      const index = accounts.value.findIndex(account => account.id === id)
      if (index !== -1) {
        accounts.value[index] = {
          ...accounts.value[index],
          ...accountData,
          updatedAt: new Date().toISOString()
        }
        await saveAccounts()
        return accounts.value[index]
      }
      throw new Error('账号不存在')
    } catch (error) {
      console.error('更新账号失败:', error)
      throw error
    }
  }

  const deleteAccount = async (id) => {
    try {
      const index = accounts.value.findIndex(account => account.id === id)
      if (index !== -1) {
        accounts.value.splice(index, 1)
        await saveAccounts()
        return true
      }
      return false
    } catch (error) {
      console.error('删除账号失败:', error)
      throw error
    }
  }

  const toggleFavorite = async (id) => {
    try {
      const account = accounts.value.find(account => account.id === id)
      if (account) {
        account.isFavorite = !account.isFavorite
        account.updatedAt = new Date().toISOString()
        await saveAccounts()
        return account.isFavorite
      }
      return false
    } catch (error) {
      console.error('切换收藏状态失败:', error)
      throw error
    }
  }

  const markAsUsed = async (id) => {
    try {
      const account = accounts.value.find(account => account.id === id)
      if (account) {
        account.lastUsed = new Date().toISOString()
        await saveAccounts()
      }
    } catch (error) {
      console.error('更新使用时间失败:', error)
    }
  }

  const updateLastUsed = async (id) => {
    try {
      const account = accounts.value.find(account => account.id === id)
      if (account) {
        account.lastUsed = new Date().toISOString()
        account.updatedAt = new Date().toISOString()
        await saveAccounts()
      }
    } catch (error) {
      console.error('更新最后使用时间失败:', error)
    }
  }

  const copyToClipboard = async (text, accountId = null) => {
    try {
      await window.electronAPI.copyToClipboard(text)
      if (accountId) {
        await markAsUsed(accountId)
      }
      return true
    } catch (error) {
      console.error('复制到剪贴板失败:', error)
      return false
    }
  }

  const addCategory = (categoryName) => {
    if (!categories.value.includes(categoryName)) {
      categories.value.push(categoryName)
    }
  }

  const getAccountById = (id) => {
    return accounts.value.find(account => account.id === id)
  }

  const getAccountsByCategory = (category) => {
    return accounts.value.filter(account => account.category === category)
  }

  return {
    // 状态
    accounts,
    categories,
    searchQuery,
    selectedCategory,
    loading,
    
    // 计算属性
    filteredAccounts,
    favoriteAccounts,
    recentAccounts,
    
    // 方法
    loadAccounts,
    saveAccounts,
    addAccount,
    updateAccount,
    deleteAccount,
    toggleFavorite,
    markAsUsed,
    updateLastUsed,
    copyToClipboard,
    addCategory,
    getAccountById,
    getAccountsByCategory
  }
})
